package com.xsf.pay.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xsf.pay.common.constants.RedisConstant;
import com.xsf.pay.common.domain.CodeMsg;
import com.xsf.pay.common.domain.Result;
import com.xsf.pay.common.exception.BusinessRunTimeException;
import com.xsf.pay.entity.dto.VerifyCodeDto;
import com.xsf.pay.service.CommonService;
import com.xsf.pay.service.RedisService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * 通用服务接口实现类
 * @author xsf
 */
@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private RedisService redisService;

    @Override
    public Result<Object> getVerifyCode(@Valid VerifyCodeDto verifyCodeDto) {
        String key = StrUtil.format(RedisConstant.USER_PHONE_CACHE, verifyCodeDto.getPhone());
        if(redisService.hasKey(RedisConstant.USER_PHONE_CACHE)){
            throw new BusinessRunTimeException(CodeMsg.CODE_SEND_ERROR);
        }
        String code = RandomUtil.randomNumbers(6);
        redisService.set(key, code, 60, TimeUnit.SECONDS);
        return Result.ok();
    }

    @Override
    public Boolean verifyCode(String phone, String code) {
        String key = StrUtil.format(RedisConstant.USER_PHONE_CACHE, phone);
        if(redisService.hasKey(key)){
            String redisCode = String.valueOf(redisService.get(key));
            if(!redisCode.equals(code)){
                throw new BusinessRunTimeException(CodeMsg.CODE_ERROR);
            }
            return true;
        }else {
            throw new BusinessRunTimeException(CodeMsg.CODE_EXPIRE);
        }
    }
}
